package edu.arizona.eller.mis.liferoulette;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import edu.arizona.eller.mis.liferoulette.db.dao.ActivityDAO;
import edu.arizona.eller.mis.liferoulette.db.dao.UserPreferenceDAO;
import edu.arizona.eller.mis.liferoulette.entity.ActivityBean;
import edu.arizona.eller.mis.liferoulette.entity.UserMessage;
import edu.arizona.eller.mis.liferoulette.entity.UserPreference;
import edu.arizona.eller.mis.liferoulette.utils.ConnectionUtils;
import edu.arizona.eller.mis.liferoulette.utils.LocUtility;

public class result extends Activity implements OnClickListener {

	Button bAccept, bRefuse;
	EditText et;
	TextView nameT,ratingT,vicinityT,typeT;
	RatingBar ratingBar;
	int accepted = 0;
	
	private String placesURL = "https://maps.googleapis.com/maps/api/place/search/json?";
	private String placesPARAMS = "location={LOCATION}&" +
			"radius={RADIUS}&" + //In meters
			"types={TYPE}&" + //Can be separated by pipes for multiple
			"sensor=true&" + //Used to identify a mobile device making request
			"key=AIzaSyB7IkFaNcSrm4ViJLA1iN4jnOqe-mvh8m0";
	
	LocUtility locUtility;
	LocationManager locManager;
	
	private static double lon,lat;
	private static String name,vicinity;
	private static JSONObject selection;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        bAccept = (Button)findViewById(R.id.acceptButton);
        bAccept.setOnClickListener(this);
        bRefuse = (Button)findViewById(R.id.refuseButton);
        bRefuse.setOnClickListener(this);
        
        nameT = (TextView)findViewById(R.id.nameText);
        //ratingT = (TextView)findViewById(R.id.ratingText);
        vicinityT = (TextView)findViewById(R.id.vicinityText);
        typeT = (TextView)findViewById(R.id.typeText);

        ratingBar = (RatingBar)findViewById(R.id.ratingBar1);

		JSONArray results = null;
		if(ConnectionUtils.getInstance().isNetworkAvailable(this)){//Check for network connectivity
			locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	        locUtility = new LocUtility(locManager);
	        
	        Location loc = locUtility.getCurrentLoc();
	       
	        if(loc !=null && loc.getLatitude() != 0 && loc.getLongitude() != 0){
	            String lat = String.valueOf(loc.getLatitude());
	            String lon = String.valueOf(loc.getLongitude());
	            
	            UserPreferenceDAO dao = new UserPreferenceDAO(getApplicationContext());
	            UserPreference radiusPref = dao.findById(1);//1 is miles preference;
	            dao.closeDAO();
	            Integer radius = Integer.parseInt(radiusPref.getValue());
	            
	            Bundle b = this.getIntent().getExtras();
	            String eventType = "Adventure";
	            if(b !=null && b.get("type") != null){
	            	eventType = b.getString("type");
	            }
	            
	            results = selectPlace(lat, lon, String.valueOf(radius*1609), eventType);
	        }else{
	        	//if no location, let the user know
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("No GPS Location available, please check that GPS is enabled and/or try again later!")
				       .setCancelable(false)
				       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   result.this.finish();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
	        }
		}else{
			//if no connection, let the user know
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("No network connection, please check WiFi or Mobile is available!")
			       .setCancelable(false)
			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   result.this.finish();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
        if(results == null || results.length() == 0){
        	nameT.setText("No Results");
            //ratingT.setText("No Results");
            vicinityT.setText("No Results");
            typeT.setText("No Results");
            ratingBar.setRating(0);

        }else{
        	int randomNum = (int) Math.ceil(Math.random() * results.length()-1);
        	try {
				selection = (JSONObject)results.get(randomNum);
				nameT.setText(selection.getString("name"));
				name = selection.getString("name");
	            //ratingT.setText(selection.getString("rating"));
	            ratingBar.setRating((float)selection.getDouble("rating"));
	            vicinityT.setText(selection.getString("vicinity"));
	            vicinity = selection.getString("vicinity");
	            JSONArray types = selection.getJSONArray("types");
	            String typesDisplay = "";
	            for(int i=0;i<types.length();i++){
	            	if(i==0){
	            		typesDisplay = types.getString(i);
	            	}else{
	            		typesDisplay += ", " + types.getString(i);
	            	}
	            }
	            typeT.setText(typesDisplay);
	            
	            JSONObject placeGeo = selection.getJSONObject("geometry");
	            JSONObject placeLoc = placeGeo.getJSONObject("location");

	            lat = placeLoc.getDouble("lat");
	            lon = placeLoc.getDouble("lng");
	            
			} catch (JSONException e) {
				e.printStackTrace();
			}
        }
	}
	
	
	
	private JSONArray selectPlace(String lat, String lon, String radius, String type){
		HttpURLConnection http = null;
		JSONObject jArray = null;
		InputStream is = null;
		try{
			String urlString = placesURL + placesPARAMS;
			urlString = urlString.replace("{LOCATION}", lat + "," + lon);
			try {
				urlString = urlString.replace("{TYPE}", URLEncoder.encode(type, "ISO-8859-1"));
			} catch (UnsupportedEncodingException e1) {
				urlString = urlString.replace("{TYPE}", URLEncoder.encode(type));
			}
			
			urlString = urlString.replace("{RADIUS}", radius);
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(urlString);
			HttpResponse response = httpclient.execute(httpget);
			if(response != null && response.getStatusLine().getStatusCode() == 200){//Check Status Code
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			    
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			    StringBuilder sb = new StringBuilder();
				String line = null;
				
				while ((line = reader.readLine()) != null) {
				    sb.append(line + "\n");
				}
		
				//try parse the string to a JSON object
				jArray = new JSONObject(sb.toString());
			}else{
				Toast.makeText(this, "Unable to connect to Google Places, please try again later.", Toast.LENGTH_LONG);
				jArray = new JSONObject();
			}
			

		
			return jArray.getJSONArray("results");
		} catch (JSONException e) {
			return null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this, "An exception occured, please contact the helpdesk.", Toast.LENGTH_LONG);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this, "An exception occured, please contact the helpdesk.", Toast.LENGTH_LONG);
		}finally{
			if(http != null){
				http.disconnect();//Close the http connection
			}
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		
		return null;
	}

	public void onClick(View v) {
		Intent i = null;
		
		if(v == bAccept){
			if (accepted == 0){
				UserPreferenceDAO upDAO = new UserPreferenceDAO(getApplicationContext());
				bAccept.setText("Directions");
				bRefuse.setText("Send to Friend");
				
				if(upDAO.getUserPreferences().get(2).getValue().equals("false")){
					bRefuse.setTextColor(Color.GRAY);
					bRefuse.setClickable(false);
				}else{
					bRefuse.setClickable(true);
				}
						
				upDAO.closeDAO();
				UserMessage um = new UserMessage();
				Toast.makeText(this, um.getAcceptMessage(),Toast.LENGTH_LONG).show();
			}
			if (accepted == 1){
				ActivityDAO dao = new ActivityDAO(getApplicationContext());
				ActivityBean a = new ActivityBean();
				a.setActivity(selection.toString());
				dao.insert(a);
				dao.closeDAO();
				
				i = new Intent(getApplicationContext(),result_maps.class);
				i.putExtra("lat", lat);
				i.putExtra("lon", lon);
				i.putExtra("name",name);
				i.putExtra("vicinity", vicinity);
				startActivity(i);
			}
			accepted = 1;
			
		}else if(v == bRefuse){
			if(accepted == 0){
				bAccept.setClickable(false);
				bAccept.setTextColor(Color.GRAY);
				bRefuse.setClickable(false);
				bRefuse.setTextColor(Color.GRAY);
				
				UserMessage um = new UserMessage();
				Toast.makeText(this, um.getRefuseMessage(),Toast.LENGTH_LONG).show();
				i = new Intent(this,main.class);
			}
			if(accepted == 1){
				i = new Intent(this,sms_send.class);
				i.putExtra("name", name);
				i.putExtra("vicinity", vicinity);

			}
		}
		if(i != null)
			startActivity(i);
		
	}
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.activity_menu, menu);
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.settingsItem:     
	        	startActivity(new Intent(this, UserPreferenceAcvitity.class));
	            break;
	        case R.id.historyItem:     
	        	startActivity(new Intent(this, HistoryActivity.class));
	            break;
	        case R.id.homeItem:     
	        	startActivity(new Intent(this, main.class));
	            break;
	    }
	    return true;
	}

}
